<template>
  <div class="face-demo">
    <template>
      <div v-if="mode === 'edit'">
        <el-input
          v-model="userName"
          placeholder="请输入用户姓名"
          :disabled="disabled"
          clearable
        ></el-input>
        <div style="margin-top: 15px;">
          <el-input
            v-model="idCard"
            placeholder="请输入身份证号码"
            @input="checkIdCard"
            :disabled="disabled"
            clearable
          ></el-input>
        </div>
        <div
          class="el-form-item__error"
          v-if="cardError"
        >身份证格式不正确！</div>
        <div
          v-if="userName && idCard && !cardError"
          style="margin-top: 10px;"
        >
          <div v-if="imgUrl">
            <img
              :src="imgUrl"
              width="400"
              height="400"
            />
          </div>
          <el-button
            v-if="!showSuccessText && !imgUrl"
            type="primary"
            round
            :disabled="disabled"
            :loading="btnLoading"
            @click="getFaceToken"
          >{{ btnText }}</el-button>
          <div v-if="showSuccessText || showErrorText">
            认证结果:
            <span
              v-if="showSuccessText"
              class="success-text"
            >
              {{ showSuccessText }}
            </span>
            <span
              v-if="showErrorText"
              class="error-text"
            >
              {{ showErrorText }}
            </span>
          </div>
        </div>
      </div>
      <div v-else>{{ value }}</div>
    </template>
  </div>
</template>

<script>
import customRequest from "../../mixins/custom-request.js"
import axios from "axios"
import dayjs from "dayjs"
import CryptoJS from "crypto-js"
export default {
  name: 'face',
  components: {},
  mixins: [customRequest],
  props: {
    value: {},
    mode: {
      default: "edit", // 编辑模式和 edit， 展示模式 view
    },
    readonly: {
      type: Boolean,
      default: false,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    // appCode: {
    //   type: String,
    //   default: "",
    // },
    // appSecret: {
    //   type: String,
    //   default: "",
    // },
    // faceComponentUrl: {
    //   type: String,
    //   default: "",
    // },
    // contextPath: {
    //   type: String,
    //   default: "",
    // },
    // fvTokenPath: {
    //   type: String,
    //   default: "",
    // },
    // faceResultPath: {
    //   type: String,
    //   default: "",
    // },
  },
  data() {
    return {
      btnText: "人脸识别",
      userName: "",
      idCard: "",
      cardError: "",
      imgUrl: null,
      resultTimer: null,
      resultInterval: 20 * 1000,
      btnLoading: false,
      showSuccessText: null,
      showErrorText: null,
      belong: '人脸识别',
      defaultErrMsg: '无效的accessToken'
    }
  },
  watch: {},
  mounted() {
    if (this.value) {
      this.idCard = this.value;
      if (this.mode == 'view') {
        this.disabled = true;
      }
    }
  },
  computed: {},
  beforeDestroy() {
    this.stopInterval()
  },
  methods: {
    checkIdCard() {
      this.$emit("input", this.idCard)
      let legalTex = /^[1-9](\d{16}|\d{13})[0-9xX]$/;
      let result = legalTex.test(this.idCard);
      if (!result && this.idCard) {
        this.cardError = true
      } else {
        this.cardError = false
      }
    },
    stopInterval() {
      clearInterval(this.resultTimer)
      this.resultTimer = null
    },
    tipErrMsg(errMsg) {
      if (!errMsg) errMsg = this.defaultErrMsg
       this.$message.error(errMsg)
       this.showErrorText = errMsg
    },
    queryResult(token, headers) {
      this.showErrorText = null;
      this.showSuccessText = null;
      // const { faceComponentUrl, contextPath, faceResultPath, appCode, appSecret } = this;
      const faceComponentUrl = this.getCodeValueByCode('FACE_COMPONENT_URL')
      const contextPath = this.getCodeValueByCode('CONTEXT_PATH')
      const faceResultPath = this.getCodeValueByCode('GET_ACCESS_CHECK_URL')
      const appCode = this.getCodeValueByCode('APP_CODE')
      const appSecret = this.getCodeValueByCode('APP_SECRET')
      const data = { faceComponentUrl, contextPath, faceResultPath, appCode, appSecret, accessToken: token }
      axios.post(`${this.preurl}api/afc/integration/accessCheck`, data, { headers }).then((res) => {
        const responseData = _.get(res, 'data', null)
        console.log("accessCheck接口成功响应数据:", responseData)
        let { errCode, errMsg, data } = responseData
        if (errCode === "20000" || errCode === 20000) {
          const { Subject, timestamp, sid, flag } = data
          if (flag) {
           const credentNo = this.idCard
           const upperSubject = _.toUpper(Subject)
          const now = dayjs()
          const date = dayjs.unix(_.toNumber(timestamp))
          const diffTime = now.diff(date, 's', true)
          console.log('当前时间:', now.unix())
          console.log('当前时间和timestamp的差值(秒):', diffTime)
          if (_.gte(diffTime, 180)) {
           this.tipErrMsg()
          } else {
           let signature = CryptoJS.SHA256(timestamp + credentNo + "-" + token + sid + timestamp).toString(CryptoJS.enc.Hex).toUpperCase()
           if (signature === upperSubject) {
              this.stopInterval()
              this.btnLoading = false
              this.imgUrl = null;
              this.showSuccessText = "认证成功"
              this.$message.success("认证成功")
            } else {
              this.tipErrMsg()
            }
           }
          } else {
            this.tipErrMsg()
          }
        } else {
          this.tipErrMsg(errMsg)
        }
      }).catch((err) => {
        console.log("请求accessCheck接口错误:", err)
      })
    },
    getFaceToken() {
      this.btnLoading = true;
      try {
        const headers = this.header
        // const { faceComponentUrl, contextPath, fvTokenPath, appCode, appSecret } = this;
        const faceComponentUrl = this.getCodeValueByCode('FACE_COMPONENT_URL')
        const contextPath = this.getCodeValueByCode('CONTEXT_PATH')
        const fvTokenPath = this.getCodeValueByCode('GET_FV_TOKEN_URL')
        const appCode = this.getCodeValueByCode('APP_CODE')
        const appSecret = this.getCodeValueByCode('APP_SECRET')
        const data = { faceComponentUrl, contextPath, fvTokenPath, appCode, appSecret, userName: this.userName, credentNo: this.idCard, isApp: false }
        console.log("getFaceToken接口入参:", data)
        axios.post(`${this.preurl}api/afc/integration/getFaceToken`, data, { headers }).then((res) => {
          const { data, errCode, errMsg } = res.data;
          console.log("getFaceToken接口成功响应数据:", data)
          if (errCode !== "20000") {
            this.btnLoading = false;
            this.$message.error(errMsg)
            return;
          }
          const { fvtoken, qrcode } = data;
          const imageType = "jpeg"
          this.imgUrl = `data:image/${imageType};base64,${qrcode}`
          this.disabled = true;
          if (fvtoken) {
            this.resultInterval /= 2;
            this.stopInterval();
            this.resultTimer = setInterval(() => {
              setTimeout(this.queryResult(fvtoken, headers), 0)
            }, this.resultInterval)
          }
        }).catch((err) => {
          this.btnLoading = false;
          console.log("请求getFaceToken接口错误:", err)
          const message = _.get(err, "response.data.errorLocalizedMessage")
          this.$message.error(message || err.message)
        })
      } catch (err) {
        this.btnLoading = false;
        console.log("调用过程报错了:", err)
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.face-demo {
  width: 100%;
}
.success-text {
  color: #67c23a;
}
.error-text {
  color: #f56c6c;
}
</style>